package com.ihr360.job.core.step;

import com.ihr360.job.core.JobInterruptedException;
import com.ihr360.job.core.entity.StepExecution;
import com.ihr360.job.core.job.builder.JobBuilderHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Policy that checks the current thread to see if it has been interrupted.
 *
 * @author Lucas Ward
 * @author Dave Syer
 *
 */
public class ThreadStepInterruptionPolicy implements StepInterruptionPolicy {

    protected final Logger logger = LoggerFactory.getLogger(JobBuilderHelper.class.getName());

    /**
     * Returns if the current job lifecycle has been interrupted by checking if
     * the current thread is interrupted.
     */
    @Override
    public void checkInterrupted(StepExecution stepExecution) throws JobInterruptedException {

        if (isInterrupted(stepExecution)) {
            throw new JobInterruptedException("Job interrupted status detected.");
        }

    }

    /**
     * @param stepExecution the current context
     * @return true if the job has been interrupted
     */
    private boolean isInterrupted(StepExecution stepExecution) {
        boolean interrupted = Thread.currentThread().isInterrupted();
        if (interrupted) {
            logger.info("Step interrupted through Thread API");
        }
        else {
            interrupted = stepExecution.isTerminateOnly();
            if (interrupted) {
                logger.info("Step interrupted through StepExecution");
            }
        }
        return interrupted;
    }

}